package com.changgou.oauth.util;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * 构建管理员令牌
 */
public class AdminToken {
    public static String creatToken(String[] roles) {
        //加载证书(读取类路径下的文件)
        ClassPathResource resource = new ClassPathResource("changgou.jks");
        //获取证书数据
        KeyStoreKeyFactory keyFactory = new KeyStoreKeyFactory(resource, "changgou".toCharArray());
        //获取证书里的一对密钥
        KeyPair keyPair = keyFactory.getKeyPair("changgou", "changgou".toCharArray());
        //获取私钥(RSA算法)
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //创建载荷
        Map<String, Object> map = new HashMap<>();
        map.put("name","xiaohong");
        map.put("age",18);
        //封装角色信息
        map.put("authorities",roles);
//        map.put("authorities",new String[]{"admin", "oauth"});
        //创建令牌，需要私钥加盐（RSA）
        Jwt jwt = JwtHelper.encode(JSON.toJSONString(map), new RsaSigner(privateKey));
        //获取令牌
        String encoded = jwt.getEncoded();
        return encoded;
    }
}
